class PerformanceMonitor {
    constructor() {
        this.updateInterval = 1000; // 每1秒更新一次
        this.maxDataPoints = 15; // 保留15个数据点，减少以保持流畅性
        this.data = {
            timestamps: [],
            cpu: [],
            memory: [],
            disk: []
        };
        this.charts = {
            cpu: null,
            memory: null,
            disk: null
        };
        this.initCharts();
        this.startMonitoring();
    }

    initCharts() {
        const chartOptions = {
            animation: false,
            grid: {
                top: 0,
                right: 0,
                bottom: 0,
                left: 0
            },
            xAxis: {
                show: false,
                type: 'category'
            },
            yAxis: {
                show: false,
                type: 'value',
                min: 0,
                max: 100
            },
            tooltip: {
                show: false
            },
            series: [{
                type: 'line',
                showSymbol: false,
                smooth: true,
                data: []
            }]
        };

        // 初始化CPU图表
        this.charts.cpu = echarts.init(document.getElementById('cpu-chart'));
        this.charts.cpu.setOption({
            ...chartOptions,
            series: [{
                ...chartOptions.series[0],
                itemStyle: { color: '#1890ff' },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(24,144,255,0.3)' },
                        { offset: 1, color: 'rgba(24,144,255,0.1)' }
                    ])
                }
            }]
        });

        // 初始化内存图表
        this.charts.memory = echarts.init(document.getElementById('memory-chart'));
        this.charts.memory.setOption({
            ...chartOptions,
            series: [{
                ...chartOptions.series[0],
                itemStyle: { color: '#52c41a' },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(82,196,26,0.3)' },
                        { offset: 1, color: 'rgba(82,196,26,0.1)' }
                    ])
                }
            }]
        });

        // 初始化磁盘图表
        this.charts.disk = echarts.init(document.getElementById('disk-chart'));
        this.charts.disk.setOption({
            ...chartOptions,
            series: [{
                ...chartOptions.series[0],
                itemStyle: { color: '#faad14' },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(250,173,20,0.3)' },
                        { offset: 1, color: 'rgba(250,173,20,0.1)' }
                    ])
                }
            }]
        });

        // 添加窗口大小变化的监听器
        window.addEventListener('resize', () => {
            Object.values(this.charts).forEach(chart => chart.resize());
        });
    }

    startMonitoring() {
        // 立即获取一次数据
        this.updateMetrics();
        
        // 开始定时更新
        this.updateTimer = setInterval(() => {
            this.updateMetrics();
        }, this.updateInterval);
    }

    async updateMetrics() {
        try {
            const response = await fetch('/api/monitoring/metrics');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            this.updateUI(data);
        } catch (error) {
            console.error('获取监控数据出错:', error);
        }
    }

    updateUI(data) {
        if (!data || !data.system) {
            console.error('无效的监控数据格式:', data);
            return;
        }

        const systemMetrics = data.system;
        
        // 更新数据数组
        this.data.cpu.push(parseFloat(systemMetrics.cpu));
        this.data.memory.push(parseFloat(systemMetrics.memory));
        this.data.disk.push(parseFloat(systemMetrics.disk));

        // 保持固定数量的数据点
        if (this.data.cpu.length > this.maxDataPoints) {
            this.data.cpu.shift();
            this.data.memory.shift();
            this.data.disk.shift();
        }

        // 更新各个迷你图表
        this.charts.cpu.setOption({
            series: [{
                data: this.data.cpu
            }]
        });
        
        this.charts.memory.setOption({
            series: [{
                data: this.data.memory
            }]
        });
        
        this.charts.disk.setOption({
            series: [{
                data: this.data.disk
            }]
        });
        
        // 更新各项指标的数值显示
        this.updateMetric('cpu-usage', systemMetrics.cpu);
        this.updateMetric('memory-usage', systemMetrics.memory);
        this.updateMetric('disk-usage', systemMetrics.disk);
    }

    updateMetric(elementId, value) {
        const element = document.getElementById(elementId);
        if (!element) {
            console.error(`找不到元素: ${elementId}`);
            return;
        }

        // 确保value是数字
        const numValue = parseFloat(value);
        if (isNaN(numValue)) {
            console.error(`无效的数值: ${value}`);
            return;
        }

        // 更新数值
        element.textContent = `${numValue.toFixed(1)}%`;
        
        // 移除现有的状态类
        element.classList.remove('warning', 'danger');
        
        // 根据数值设置状态类
        if (numValue > 90) {
            element.classList.add('danger');
        } else if (numValue > 70) {
            element.classList.add('warning');
        }
    }
}

// 初始化性能监控
document.addEventListener('DOMContentLoaded', () => {
    new PerformanceMonitor();
}); 